const path = require('path');
const webpack = require('webpack');
const CompressionWebpackPlugin = require('compression-webpack-plugin');

function resolve(dir) {
    return path.join(__dirname, dir);
}
const {
    VueCDN,
    VueRouterCDN,
    VuexCDN,
    AxiosCDN,
    nprogressCDN,
    clipboardCDN,
    // datasetCDN,
    jscookieCDN
} = require('./src/plugins/cdn');

const isProd = process.env.NODE_ENV === 'production';
const assetsCDN = {
    // webpack build externals
    externals: {
        vue: 'Vue',
        'vue-router': 'VueRouter',
        vuex: 'Vuex',
        axios: 'axios',
        // nprogress: 'NProgress',
        clipboard: 'ClipboardJS',
        // '@antv/data-set': 'DataSet',
        'js-cookie': 'Cookies'
    },
    css: [],
    js: [
        VueCDN,
        VueRouterCDN,
        VuexCDN,
        AxiosCDN,
        nprogressCDN,
        clipboardCDN,
        // datasetCDN,
        jscookieCDN
    ]
};
const productionGzipExtensions = ['html', 'js', 'css', 'svg'];

// const argv = JSON.parse(process.env.npm_config_argv)
// const config = {}
let idx = 2
// const cooked = argv.cooked
// const length = argv.cooked.length

// while ((idx += 2) <= length) {
//   console.log(idx)
//   config[cooked[idx - 2]] = cooked[idx - 1]
// }
// const port = config['--port'] || 8999;
const port = 8999;

module.exports = {
    productionSourceMap: false,
    outputDir: 'dist',
    publicPath: '/',
    lintOnSave: false,
    devServer: {
        port: port,
        open: true,
        proxy: {
            '/api': {
                // target: 'http://172.25.80.133:8840',//代理地址，这里设置的地址会代替axios中设置的baseURL
                // target: 'http://36.26.76.196:28688',
                // target: 'http://172.26.153.15:28888',
                target: 'http://110.40.128.240:28888/api',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': '/'
                }
            }
        }
    },
    css: {
        extract: isProd,
        loaderOptions: {
            sass: {
                prependData: `@import "~@/styles/variables.scss";`
            },
            less: {
                lessOptions: {
                    // If you are using less-loader@5 please spread the lessOptions to options directly
                    modifyVars: {
                        'primary-color': '#4165d7',
                        'link-color': '#4165d7',
                        'font-size-base': '12px'
                    },
                    javascriptEnabled: true
                }
            }
        }
    },

    configureWebpack: {
        name: process.env.VUE_APP_BASE_NAME,
        resolve: {
            alias: {
                '@': resolve('src')
            }
        },
        externals: isProd ? assetsCDN.externals : {},
        plugins: [
            // Ignore all locale files of moment.js
            new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
            // 配置压缩
            new CompressionWebpackPlugin({
                algorithm: 'gzip',
                test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
                threshold: 10240,
                minRatio: 0.8
            }),
            //maxChunks：使用大于或等于 1 的值，来限制 chunk 的最大数量。使用 1 防止添加任何其他额外的 chunk，这是因为entry/main chunk 也会包含在计数之中。
            //minChunkSize: 设置 chunk 的最小大小。
            //在合并 chunk 时，webpack 会尝试识别出具有重复模块的 chunk，并优先进行合并。任何模块都不会被合并到 entry   chunk 中，以免影响初始页面加载时间。
            new webpack.optimize.LimitChunkCountPlugin({
                maxChunks: 5,
                minChunkSize: 100
            })
        ]
    },
    chainWebpack(config) {
        config.resolve.symlinks(true);
        config.plugins.delete('prefetch');
        config.plugins.delete('preload');
        // 设置svg
        config.module
            .rule('svg')
            .exclude.add(resolve('src/icons'))
            .end();
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include.add(resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
            .end();

        //设置开发环境sourceMap
        config.when(!isProd, config => config.devtool('cheap-source-map'));
        //生产环境
        if (isProd) {
            config.optimization.splitChunks({
                chunks: 'all',
                cacheGroups: {
                    libs: {
                        name: 'chunk-libs',
                        test: /[\\/]node_modules[\\/]/,
                        priority: 10,
                        chunks: 'initial'
                    },
                    commons: {
                        name: 'chunk-commons',
                        test: /[\\/]src[\\/]js[\\/]/,
                        minChunks: 2, //  minimum common number
                        priority: 5,
                        reuseExistingChunk: true
                    }
                },
                minSize: 30000, // 提取出的新chunk在两次压缩(打包压缩和服务器压缩)之前要大于30kb
                maxSize: 100000, // 提取出的新chunk在两次压缩之前要小于多少kb，默认为0，即不做限制
                minChunks: 1, // 被提取的chunk最少需要被多少chunks共同引入
                maxAsyncRequests: 5, // 最大按需载入chunks提取数
                maxInitialRequests: 3, // 最大初始同步chunks提取数
                automaticNameDelimiter: '~', // 默认的命名规则（使用~进行连接）
                name: true,
                cacheGroups: {
                    // 缓存组配置，默认有vendors和default
                    vendors: {
                        test: /[\\/]node_modules[\\/]/,
                        minChunks: 5,
                        priority: 10,
                        reuseExistingChunk: true
                    },
                    default: {
                        minChunks: 2,
                        priority: -20,
                        reuseExistingChunk: true
                    }
                }
            });

            config.plugin('html').tap(args => {
                args[0].cdn = assetsCDN;
                return args;
            });

            config.optimization.runtimeChunk('single');

            //去除生产环境debugger 和console
            config.optimization.minimizer('terser').tap(args => {
                args[0].terserOptions.compress.warnings = false;
                args[0].terserOptions.compress.drop_console = true;
                args[0].terserOptions.compress.drop_debugger = true;
                args[0].terserOptions.compress.pure_funcs = ['console.*'];
                return args;
            });
            //g-zip开启
            config.plugin('CompressionWebpackPlugin').use(CompressionWebpackPlugin, [
                {
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: /\.js$|\.css/, //匹配文件名
                    threshold: 10240, //对超过10k的数据压缩
                    minRatio: 0.8
                }
            ]);
            //打包大小分析
            if (process.env.npm_config_report) {
                config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin);
            }
        }
    }
};
